//
//  MainWindowController.m
//  SolarSimple
//
//  Created by Marcelo Alves on 13/10/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "MainWindowController.h"
#import "PrefsWindowController.h"


@implementation MainWindowController
- (BOOL)outlineView:(NSOutlineView *)outlineView isGroupItem:(id)item{
	if ([outlineView levelForItem:item] == 0) {
    [outlineView performSelector:@selector(expandItem:) withObject:item afterDelay:0.01f];
    return YES;
  }
	return NO;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView shouldSelectItem:(id)item {
	if ([outlineView levelForItem:item] == 0) return NO;
	return YES;
}
- (void)outlineView:(NSOutlineView *)theOutlineView willDisplayOutlineCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item {
  if (item) {
//    [cell setSize:NSMakeSize(1000,1000)];
    [cell setTransparent:YES];
  }
} 

-(void) awakeFromNib {
  // TODO: move the folder creation to another class
  NSString *solarSeekBaseFolder = [@"~/Library/Application Support/SolarSeek/1.0" stringByExpandingTildeInPath];
  NSString *solarSeekDownloadFolder = [@"~/Downloads/SolarSeek/Downloads" stringByExpandingTildeInPath];
  NSString *solarSeekUploadFolder = [@"~/Downloads/SolarSeek/Uploads" stringByExpandingTildeInPath];
  
  NSFileManager *fileManager = [NSFileManager defaultManager];

  if ([fileManager fileExistsAtPath:solarSeekBaseFolder] == NO)
    [fileManager createDirectoryAtPath:solarSeekBaseFolder withIntermediateDirectories:YES attributes:NULL error:NULL];

  if ([fileManager fileExistsAtPath:solarSeekDownloadFolder] == NO)
    [fileManager createDirectoryAtPath:solarSeekDownloadFolder withIntermediateDirectories:YES attributes:NULL error:NULL];
  
  if ([fileManager fileExistsAtPath:solarSeekUploadFolder] == NO)
    [fileManager createDirectoryAtPath:solarSeekUploadFolder withIntermediateDirectories:YES attributes:NULL error:NULL];
 
  museekdController = [[[NSApplication sharedApplication] delegate] museekdController];
}

-(IBAction) startMuseekd:(id)sender {
  [museekdController startMuseekd];
}

-(IBAction) stopMuseekd:(id)sender {
  [museekdController stopMuseekd];
}

-(IBAction) createConfigFile:(id)sender {
  [loginInformationSheet orderOut:nil];
  [NSApp endSheet:loginInformationSheet];
  
  
  NSString *user = [username stringValue];
  NSString *pass = [password stringValue];
  
  
  // todo : move this code to museek controller, in a method called setUser:andPassword:
  NSString *path = [NSString stringWithFormat:@"%@/Contents/Resources/config.xml", [[NSBundle mainBundle] bundlePath]];
  NSString *xml = [NSString stringWithContentsOfFile:path];
  xml = [xml stringByReplacingOccurrencesOfString:@"#{USER}" withString:user]; 
  xml = [xml stringByReplacingOccurrencesOfString:@"#{PASSWORD}" withString:pass];
  xml = [xml stringByReplacingOccurrencesOfString:@"~" withString:[@"~/" stringByExpandingTildeInPath]];
  
  NSString *destination = [@"~/Library/Application Support/SolarSeek/1.0/config.xml" stringByExpandingTildeInPath];
  [xml writeToFile:destination atomically:YES encoding:NSUTF8StringEncoding error:NULL];
  
  // calling mushare to add shares from ~/Downloads/SolarSeek/Shared
  
  //todo: add active/passive transfers in the user/password sheet

  // starting museekd
  [self startMuseekd:sender];
}

-(IBAction) askForUsernameAndPassword:(id)sender {
  [NSApp beginSheet:loginInformationSheet modalForWindow:[self window] modalDelegate:self didEndSelector:NULL contextInfo:NULL];
}

-(IBAction) search:(id) sender {
  NSString *value = [searchBox stringValue];
  
  if ([value compare:@""] != NSOrderedSame)
    [museekdController search:[searchBox stringValue]];
}

// opens the preferences window
- (IBAction)openPreferences:(id)sender{
  [[PrefsWindowController sharedPrefsWindowController] showWindow:nil];
}

-(IBAction) displaySearchResultsPane:(id)sender {
  NSLog(@"Should display the search result pane");
}

-(NSArray *) sidebarSortDescriptors {
	if (sidebarSortDescriptors == nil) {
		id orderDescriptor = [[NSSortDescriptor alloc] initWithKey: @"order" 
																										 ascending: YES];
		
		id nameDescriptor = [[NSSortDescriptor alloc] initWithKey: @"name"
																										ascending: YES
																										 selector: @selector(localizedCaseInsensitiveCompare:)];
		
		sidebarSortDescriptors = [NSArray arrayWithObjects:orderDescriptor, nameDescriptor, nil];
	}
	
	return sidebarSortDescriptors;
}

-(IBAction) changeView:sender {
	int index = [sender selectedRow];
	if (index < 0) return;
	
	id itemAtRow = [sender itemAtRow:index];
	if (!itemAtRow) return;
	
  id desiredViewController = NULL;
	SidebarItem *selectedItem = [itemAtRow representedObject];

	if ([selectedItem.type intValue] == searchType && selectedItem.parent != nil) {
    desiredViewController = [self searchView];
    [desiredViewController setValue:[selectedItem valueForKey:@"tag"] forKey:@"currentTicket"];
  }
  
  
  if (desiredViewController) 
    [[[NSApplication sharedApplication] delegate] changeView:desiredViewController];
  
}
  
-(id) downloadView {
  return [[[NSApplication sharedApplication] delegate] downloadView];
}

-(id) searchView {
  return [[[NSApplication sharedApplication] delegate] searchView];
}


@end
